package cn.jdy.xdgaj.web;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.jdy.authority.entity.User;
import cn.jdy.authority.service.UserService;
import cn.jdy.common.ctrl.BaseCtrl;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.safe.SafeUtil;
import cn.jdy.framework.util.DateUtil;
import cn.jdy.framework.util.NginxPurgeCacheUtil;
import cn.jdy.framework.util.ValidationUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.platform.service.ConfService;
import cn.jdy.plugins.entity.Member;
import cn.jdy.xdgaj.entity.XdgajNews;
import cn.jdy.xdgaj.service.XdgajNewsService;

/**
 * @desc  通知通报控制类
 * @author ningqian	
 * @date   2016-10-26
 */
@Controller
@RequestMapping("/Xdgajcolumns")
public class XdgajColumnsCtrl extends BaseCtrl {
	@Autowired
	private XdgajNewsService columnsService;
	@Autowired
	private ConfService confService;
	@Autowired
	private UserService userService;
	
	/**
	 * 公告栏
	 * @param Notice
	 * @return
	 */
	@RequestMapping("/index.html")
	public ModelAndView query(XdgajNews columns) {
		ModelAndView mv = new ModelAndView("/columns/columnsList.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			// 设置分页信息
			if (columns.getiDisplayLength() == 0)
				columns.setiDisplayLength(12); // 默认长度9
			if (columns.getPageNo() <= 0)
				columns.setPageNo(1); // 默认页数1
			columns.setiDisplayStart((columns.getPageNo() - 1)
					* columns.getiDisplayLength()); // 显示起始索引
			//columns.setStatus("5");// 状态 0：无效，1：有效
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			columns.setIscolums("1");;
			if (columns.getKeyword() != null && !columns.getKeyword().trim().isEmpty()) {
				mv.addObject("dataList",columnsService.queryByLike(columns, columns.getKeyword()));
				mv.addObject("total", columnsService.queryByLikeCount(columns, columns.getKeyword()));
			} else {
				
				
				List<XdgajNews> dataList=columnsService.queryTa(columns);
				mv.addObject("total", columnsService.countTa(columns));
				
				/*** 统计还要多少要签收  开始 */
				for(XdgajNews x : dataList){
					List<String> realAssos = new ArrayList<String>(); //已签收
					List<String> notAssos = new ArrayList<String>();  //未签收
					String status = x.getSignStatus();
					int tempIndex=0;
					String[] zhiduis = null;
					String[] assos = null;
					if(null != x.getSignDepartment() && !"".equals(x.getSignDepartment())){
						assos = x.getSignDepartment().split(";");
					}
					int len = 0,cnt=0;
					//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
					if(status!=null && status!=""){
						zhiduis = status.split(",");//已签收单位String数组
					}
					if(null != assos){
						for(int i=0;i<assos.length;i++){
							if((assos[i]!=null)){
								realAssos.add(cnt, assos[i]);
								//未签收
								if(zhiduis!=null && zhiduis.length>0){
									int tempCnt=0;
									for(int it=0;it<zhiduis.length;it++){
										if(!(assos[i].equals(zhiduis[it]))){
											tempCnt++;
										}
									}
									if(tempCnt==zhiduis.length){
										notAssos.add(tempIndex, assos[i]);
										tempIndex++;
									}
								}else{
									notAssos.add(cnt, assos[i]);
								}
								cnt++;
							}
						}
					}
					 if(realAssos.size()>0){
						 x.setSignStatus(notAssos.size()+"");//用这个字段迭代到前台			
						}else{
							x.setSignStatus("-1");
						}
					
				}
				/***  统计还要多少要签收  结束*/
				mv.addObject("dataList", dataList);
			}
			mv.addObject("pageNo", columns.getPageNo());
			mv.addObject("size", columns.getiDisplayLength());
			mv.addObject("columns", columns);
			mv.addObject("key", columns.getKeyword()); 
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 通知通报详细内容页
	 * @param id
	 * @return
	 */
	@RequestMapping("/show-{id}.html")
	public ModelAndView queryDetail(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/columns/columnsDetail.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		try {
			XdgajNews columns = columnsService.find(id);
			mv.addObject("columns", columns);
			// 增加一次查看
			if (columns != null) {
				columns.setReadTimes(columns.getReadTimes() == null ? 1 : columns
						.getReadTimes() + 1);
				columnsService.update(columns);
			}
			//特警
			String status = columns.getSignStatus();  //状态 0：未签收，1：已签收
			String[] zhiduis = null;
			String[] assos = columns.getSignDepartment().split(";");
			List<String> realAssos = new ArrayList<String>();
			List<String> notAssos = new ArrayList<String>();
			int len = 0,cnt=0;
//			if(status!=null && status!=""){
//				zhiduis = columns.getTeams().split(",");
//				len = status.length();
//			}
//			mv.addObject("names", zhiduis);//已签收的支队名称 tj
//			mv.addObject("number", len);//已签收的支队数目 tj
			//公安-签收状态有别于特警，直接加入签收用户名，用,逗号分隔
			if(status!=null && status!="" && status!="0"){  //状态为已签收
				zhiduis = status.split(",");//已签收单位String数组
			}
			int tempIndex=0;
			for(int i=0;i<assos.length;i++){
				if((assos[i]!=null)){
 					realAssos.add(cnt, assos[i]);
					//未签收
					if(zhiduis!=null && zhiduis.length>0){
						int tempCnt=0;
						for(int it=0;it<zhiduis.length;it++){
							if(!(assos[i].equals(zhiduis[it]))){
								tempCnt++;
							}
						}
						if(tempCnt==zhiduis.length){
							notAssos.add(tempIndex, assos[i]);
							tempIndex++;
						}
					}else{
						notAssos.add(cnt, assos[i]);
					}
					cnt++;
				}
			}
//			mv.addObject("numbers", zhiduis.length);//已签收数
//			mv.addObject("totalNums", realAssos.size());//需要签收总数
			mv.addObject("realAssos", realAssos);//需要签收的单位gaj
			mv.addObject("signAssos", zhiduis);//已签收的支队名称 gaj
			mv.addObject("notAssos", notAssos);//未签收的支队名称 gaj
			mv.addObject("id", id);//未签收的支队名称 gaj
			
			// 获得系统所有签收单位
			List<ConfValue> list = confService.queryByType(72,null);
			mv.addObject("deptList", list);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "通知通报详细内容页异常", e);
		}
		return mv;
	}

	/**
	 * 首页初始化
	 * @param notice
	 * @return
	 */
	@RequestMapping("/ind")
	@ResponseBody
	public Map<String, Object> queryN(XdgajNews columns) {
		Map<String, Object> resp = new HashMap<>();
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		try {
			// 设置分页信息
			if (columns.getiDisplayLength() == 0)
				columns.setiDisplayLength(8); // 默认长度10
			if (columns.getPageNo() <= 0)
				columns.setPageNo(1); // 默认页数1
			columns.setiDisplayStart((columns.getPageNo() - 1)
					* columns.getiDisplayLength()); // 显示起始索引
			//columns.setStatus("5");// 状态 0：无效，1：有效,3:置顶
			// 当关键字不为null并且不为空时，通过关键字全分类模糊查询
			// 反之，查询当前分页状态下的信息
			columns.setIscolums("1");
			if (columns.getKeyword() != null && !columns.getKeyword().trim().isEmpty()) {
				resp.put("dataListTop",columnsService.queryTopOne());
				resp.put("dataList",columnsService.queryByLike(columns, columns.getKeyword()));
			} else {
			//	List<Columns> rs = columnsService.queryTopOne();
				List<XdgajNews> rs = columnsService.queryTop(columns);
				//int lens = rs.size()+rst.size();
				int lens = rs.size();
				int tpi = 0;
			/*	for(int tps=rs.size();tps<lens;tps++){
					rs.add(tps, rst.get(tpi));
					tpi++;
				}*/
				resp.put("dataList", rs);
				List<Integer> numbersGAJ = new ArrayList<Integer>();
				List<Integer> numsGAJ = new ArrayList<Integer>();
				for(int i=0;i<lens;i++){
					XdgajNews temp = rs.get(i);
					String status = temp.getSignStatus();
					int cnt=0;
					if(status!=null && status!=""){
						cnt=status.split(",").length;//gaj signed
					}
					numbersGAJ.add(i, cnt);//公安局已签收数目
					String[] tempAs = null;
					if(null != temp.getSignDepartment() && !"".equals(temp.getSignDepartment())){
						tempAs = temp.getSignDepartment().split(";");
					}
					int nums=0;
					if(null != tempAs){
						for(int j=0;j<tempAs.length;j++){
							if(tempAs[j] != null){
								nums++;
							}
						}
					}
					numsGAJ.add(i, nums);//公安局需要签收的单位数目
				}
				resp.put("numbersGAJ",numbersGAJ);
				resp.put("numsGAJ",numsGAJ);
			}
			resp.put("pageNo",columns.getPageNo());
			resp.put("size",columns.getiDisplayLength());
			resp.put("columns",columns);
			resp.put("key",columns.getKeyword());
			resp.put("weekdays",weekdays);
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询通知通报异常", e);
		}
		return resp;
	}
	//useless flowings.
	/**
	 * 查询列表
	 * @param Notice
	 * @return
	 */
	@RequestMapping("/myNotice")
	public ModelAndView myNotice(XdgajNews columns) {
		ModelAndView mv = new ModelAndView("/my/myColumnsInfo.jsp");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				columns.setUserid(mbo.getId());
				// 设置分页信息
				if (columns.getiDisplayLength() == 0)
					columns.setiDisplayLength(10); // 默认长度5
				if (columns.getPageNo() <= 0)
					columns.setPageNo(1); // 默认页数1
				columns.setiDisplayStart((columns.getPageNo() - 1)
						* columns.getiDisplayLength()); // 显示起始索引
				mv.addObject("dataList", columnsService.query(columns));
				mv.addObject("pageNo", columns.getPageNo());
				mv.addObject("size", columns.getiDisplayLength());
				mv.addObject("total", columnsService.count(columns));
				mv.addObject("columns", columns);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 删除新闻
	 * @param Notice
	 * @return
	 */
	@RequestMapping("/delColumns")
	public ModelAndView delNotice(XdgajNews columns, Long id) {
		ModelAndView mv = new ModelAndView("redirect:/Xdgajcolumns/myColumns");
		try {
			Member mbo = (Member) session.getAttribute("user");
			if (mbo == null) {
				mv.setViewName("404.jsp");
			} else {
				columnsService.delete(id);
			}
		} catch (Exception e) {
			BaseLog.e(this.getClass(), "查询异常", e);
		}
		return mv;
	}

	/**
	 * 初始化新闻
	 * @param Notice
	 * @return
	 */
	@RequestMapping("/initColumns")
	public ModelAndView initNotice(XdgajNews columns, Long id) {
		ModelAndView mv = new ModelAndView("/my/columnsDetail.jsp");
		mv.addObject("column",
				this.confService.queryByType(null/*GlobalConstant.TYPE_Notice*/, 9667L));
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			columns = columnsService.find(id);
			mv.addObject("data", columns);
		}
		return mv;
	}

	/**
	 * 保存新闻
	 * @param Notice
	 * @return
	 */
	@RequestMapping("/saveColumns")
	public ModelAndView saveNotice(XdgajNews columns) {
		ModelAndView mv = new ModelAndView("redirect:/Xdgajcolumns/myColumns");
		Member mbo = (Member) session.getAttribute("user");
		if (mbo == null) {
			mv.setViewName("404.jsp");
		} else {
			columns.setUserid(mbo.getId());
			columns.setCreateTime(DateUtil.getCurrentDate2());
			columnsService.saveOrUpdate(columns);
		}
		return mv;
	}

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit() {
		return edit(null);
	}

	/**
	 * 编辑
	 * @param id
	 * @return
	 */
	@RequestMapping("/edit/{id}")
	public ModelAndView edit(@PathVariable Long id) {
		ModelAndView mv = new ModelAndView("/columns/editColumnsDetail.jsp");
		//襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
		
		mv.addObject("data", id==null||id==0 ? id : this.columnsService.find(id));
		return mv;
	}

	/**
	 * 保存（更新）新闻
	 * @param news
	 * @return
	 */
	@RequestMapping("/adminSave")
	public ModelAndView save(XdgajNews columns, Long pid) {
		ModelAndView mv = new ModelAndView("/columns/columnsOk.jsp");
		try {
			if(columns.getId()==null) {
				// 新增通知通报
				if(columns.getFalseCreateTime() == null || columns.getFalseCreateTime() == ""){
					columns.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.columnsService.save(columns);
			} else {
				//更新修改通知通报
				// 新增通知通报
				if(columns.getFalseCreateTime() == null || columns.getFalseCreateTime() == ""){
					columns.setFalseCreateTime(DateUtil.getCurrentDate(DateUtil._DEFAULT2));
				}
				this.columnsService.update(columns);
		    // 清理文章缓存
		    NginxPurgeCacheUtil.purge(2, columns.getId());
			}
		} catch(Exception e) {
			BaseLog.e(getClass(), "保存异常！", e);
		}

		return mv;
	}
	/**
	 * 襄阳市公安局
	 * 签收通知通报：多个用户均需要签收
	 * @param id
	 * @param name 登录用户名 String
	 * @return
	 */
	@RequestMapping("/signed/{id}")
	public ModelAndView signeds(@PathVariable Long id, String name) {
		ModelAndView mv = new ModelAndView("redirect:/Xdgajcolumns/show-"+id+".html");
		XdgajNews data = this.columnsService.find(id);
		
		String[] assos = data.getSignDepartment().split(";");
		int lens = assos.length;
		String statuses = data.getSignStatus();
		if(statuses==null){
			for(int iter=0;iter<lens;iter++){
				if(assos[iter]!=null && assos[iter].equals(name)){
					data.setSignStatus(name);//将状态1换成用户名
				}
			}
		}else{
			for(int iter=0;iter<lens;iter++){
				//同一账户重复签收无影响
				if(assos[iter]!=null && statuses.indexOf(name)==-1 && assos[iter].equals(name)){
					data.setSignStatus(statuses+","+name);
				}
			}
		}
		this.columnsService.update(data);
		return mv;
	}
	
	/**
	   * 签收登陆
	   */
	  @RequestMapping("/login/{id}")
	  public ModelAndView loginMores(@PathVariable Long id) {
	    ModelAndView mv = new ModelAndView("/columns/login.jsp");
	  //襄阳市公安局，需要加入当前时间段周数
		Date datetime = new Date();
		int weekdays = datetime.getDay();
		mv.addObject("weekdays",weekdays);
	  		
		mv.addObject("id", id);
	    return mv;
	  }
	  
	  /**
		 * 襄东公安分局
		 * 先验证登陆信息；通过后签收
		 * 签收通知通报：多个用户均需要签收
		 * @param id
		 * @param name 登录用户名 String
		 * @return
		 */
	  @RequestMapping("/signes/{id}")
		public ModelAndView signeds(@PathVariable Long id, String username,String password) {
			ModelAndView mv = new ModelAndView("redirect:/Xdgajcolumns/show-"+id+".html");
			
			/*校验输入信息是否合法*/
			String str = "";//提示信息
			if(ValidationUtil.isEmpty(username)) {
				str = "请输入用户名";// 请输入用户名或手机号
			} else if(ValidationUtil.isEmpty(password)) {
				str = "请输入密码";// 请输入密码
			}
			if("".equals(str)) {
				User member = userService.findMemberByUsername(username);
				if(null != member) {
					if(SafeUtil.md5(password).substring(8, 16).equals(member.getPasswd())) {
						//登陆成功-则进行点击登录进行签收
						XdgajNews data = this.columnsService.find(id);
						
						String[] assos = data.getSignDepartment().split(";");
						int lens = assos.length;
						String statuses = data.getSignStatus();
						if(statuses==null){
							for(int iter=0;iter<lens;iter++){
								if(assos[iter]!=null && assos[iter].equals(username)){
									data.setSignStatus(username);//将状态1换成用户名
								}
							}
						}else{
							for(int iter=0;iter<lens;iter++){
								//同一账户重复签收无影响 如果先签收jwbzb,接着签收jw此法出错
//								if(assos[iter]!=null && statuses.indexOf(username)==-1 && assos[iter].equals(username)){
								if(assos[iter]!=null && assos[iter].equals(username)){
									if (username.equals("jjzd")) {
										if(statuses.indexOf("gsjjzd")!=-1){//如果有
											if(statuses.indexOf("jjzd", statuses.indexOf("gsjjzd")+6) ==-1){//随后没有jw
												data.setSignStatus(statuses+","+username);
											}
										}else{
											data.setSignStatus(statuses+","+username);
										}
									} else{
										String strArry [] = statuses.split(",");
										List<String> list = Arrays.asList(strArry);
										if(!list.contains(username)){
											data.setSignStatus(statuses+","+username);
										}
									}
								}
							}
						}
						this.columnsService.update(data);
					}else{
						//登陆失败
						mv.setViewName("columns/login.jsp");
						mv.addObject("msg", "输入的密码错误!");
					}
				}else{
					mv.setViewName("columns/login.jsp");
					mv.addObject("msg", "该用户不存在!");
				}
			}else{
				mv.setViewName("columns/login.jsp");
				mv.addObject("msg", "请输入用户名或密码");
			}
			
			return mv;
		}
		
		
		
		/**
		 * 获取所有签收单位
		 * @return
		 */
		@RequestMapping("/listXdQsdw")
		@ResponseBody
		public Map<String, Object> listXdQsdw() {
			Map<String, Object> jsonMap = new HashMap<String, Object>();
			List<ConfValue> list = new ArrayList<ConfValue>();
			try {
				// 获得系统所有签收单位
				list = confService.queryByType(72,null);
				jsonMap.put("dataList", list);
			} catch(Exception e) {
				BaseLog.e(this.getClass(), "listXdQsdw 获取系统所有签收单位信息有误", e);
			}
			return jsonMap;
		}
}
